package com.hmall.order.listener;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.feign.clients.ItemClient;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class OrderListener {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private ItemClient client;

    /**
     * 定义延迟队列，监听订单的支付状态
     *
     * @param orderId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "timer.queue"),
            exchange = @Exchange(name = "order.direct",type = ExchangeTypes.TOPIC
            ,delayed = "true"),
            key = "timeOut"
    ))
    public void listenOrderPayStatus(String orderId) throws IOException {
        log.info("收到的延迟消息：{}", orderId);
        Order order = orderService.getById(orderId);
        Integer status = order.getStatus();
        if (status == 1) {
            // 修改订单信息
            order.setStatus(5);
            order.setUpdateTime(new Date());
            order.setCloseTime(new Date());
            orderService.updateById(order);

            // 业务回滚 恢复库存数量
            LambdaQueryWrapper<OrderDetail> OrderDetailQueryWrapper = new LambdaQueryWrapper<>();

            OrderDetailQueryWrapper.eq(OrderDetail::getOrderId, orderId);

            OrderDetail orderDetail = orderDetailService.getOne(OrderDetailQueryWrapper);


            client.restoreStock(orderDetail.getItemId(), orderDetail.getNum());

            Map<String, Object> map = new HashMap<>();
            map.put("order_id", orderId);
            orderDetailService.removeByMap(map);
        }


    }
}
